﻿using System;
using System.Text;

public static class Base64Util
{
    public static string Encode(byte[] buf)
    {
        return Convert.ToBase64String(buf);
    }
    public static string Encode(string plainText)
    {
        if (string.IsNullOrEmpty(plainText))
            return string.Empty;

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        return Convert.ToBase64String(plainTextBytes);
    }

    public static string Decode(string base64EncodedText)
    {
        if (string.IsNullOrEmpty(base64EncodedText))
            return string.Empty;

        // 计算需要添加的填充字符个数
        int paddingCount = base64EncodedText.Length % 4;
        if (paddingCount > 0)
        {
            paddingCount = 4 - paddingCount;
            base64EncodedText += new string('=', paddingCount);
        }

        //try
        //{
        byte[] base64Bytes = Convert.FromBase64String(base64EncodedText);
        return Encoding.UTF8.GetString(base64Bytes);
        //}
        //catch (Exception ex)
        //{
        //    // Handle the exception according to your needs
        //    Console.WriteLine($"Error decoding base64: {ex.Message}");
        //    return string.Empty;
        //}
    }
}
